<template>
  <Dialog
    class="edit-dialog"
    title="新增"
    :visible.sync="dialogVisible"
    @submit="submit"
  >
    <el-form v-model="formData" label-width="120px">
      <el-form-item label="分类名称" required>
        <el-input v-model.trim="formData.typeName" />
      </el-form-item>
      <el-form-item label="分类英文名称" required>
        <el-input v-model.trim="formData.enName"
      /></el-form-item>
      <el-form-item label="分类图标" required>
        <Upload
          typeName="iconFile"
          :showFileList="false"
          :fileList="iconFileList"
          :validatorFn="validatorFn"
        />
      </el-form-item>
      <el-form-item label="分类箭头" required>
        <Upload
          typeName="arrowFile"
          :showFileList="false"
          :fileList="arrowFileList"
          :validatorFn="validatorFn"
        />
      </el-form-item>
      <el-form-item label="分类背景颜色" required>
        <el-radio-group v-model="formData.colorCode">
          <el-radio
            :label="item.start + ',' + item.end"
            v-for="(item, index) of colorCodeList"
            :key="index"
          >
            <div class="color-box" :style="styleFn(item)"></div>
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <Progress v-if="showProgress" :percentageNum="percentageNum" />
  </Dialog>
</template>

<script>
import { inOrUpProductType } from "@/api";
import { getUploadKey, ossUpload, getFileList, delFile } from "@/api/upload";
import Upload from "@/components/upload";
export default {
  name: "EditCategory",
  components: {
    Upload
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    info: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      //对话框状态--------------------------------------------
      dialogVisible: this.visible,
      //分类图标列表--------------------------------------------
      iconFileList: [],
      //分类箭头列表--------------------------------------------
      arrowFileList: [],
      // 上传凭证
      uploadKeyList: [],
      //需要删除的文件列表
      deleteFileList: [],
      //总文件列表--------------------------------------------
      allFileList: [],
      //上传文件数--------------------------------------------
      uploadFileNum: 0,
      //文件上传数--------------------------------------------
      uploadSuccessNum: 0,
      //颜色列表--------------------------------------------
      colorCodeList: [
        { start: "#580FFD", end: "#A610FD" },
        { start: "#E63327", end: "#B439F4" },
        { start: "#E629B8", end: "#F339F5" },
        { start: "#0D6FCF", end: "#1EE1D5" },
        { start: "#FF078A", end: "#FE043B" },
        { start: "#AB10FD", end: "#FA11FD" },
        { start: "#FE4812", end: "#FEA246" },
        { start: "#13BCB6", end: "#40F2B9" },
        { start: "#FF4EAA", end: "#FF9EB3" },
        { start: "#FF5656", end: "#FFADA2" },
        { start: "#5DC257", end: "#A3ED8F" },
        { start: "#F7E778", end: "#B18B38" },
        { start: "#F9C937", end: "#FFE000" },
        { start: "#FFE240", end: "#FF4A6C" },
        { start: "#0066FF", end: "#66D2FF" },
        { start: "#0DD5E2", end: "#FF3CF8" },
        { start: "#FF3CF8", end: "#0AE6FE" },
        { start: "#FF006C", end: "#FF9900" },
        { start: "#37D237", end: "#00EAFF" },
        { start: "#C58F49", end: "#FFE5AD" }
      ],
      formData: {
        typeName: "",
        enName: "",
        colorCode: "",
        uuid: ""
      },
      // 当前上传文件列表
      currentUploadList: [],
      //是否显示进度
      showProgress: false
    };
  },

  created() {
    this.editInit();
  },

  watch: {
    //监听对话框状态--------------------------------------------
    dialogVisible(newVal) {
      this.$emit("update:visible", newVal);
    }
  },
  computed: {
    percentageNum() {
      let currentUpload = 0;
      let total = 0;
      this.currentUploadList.forEach(item => {
        currentUpload += item.loaded;
        total += item.total;
      });
      return ((currentUpload / total) * 100) | 0;
    }
  },
  methods: {
    //编辑初始化--------------------------------------------
    editInit() {
      this.$set(this.formData, "typeName", this.info.typeName);
      this.$set(this.formData, "enName", this.info.enName);
      this.$set(this.formData, "colorCode", this.info.colorCode);
      this.$set(this.formData, "uuid", this.info.uuid);

      //查询文件--------------------------------------------
      const params = {
        page: 0,
        pageSize: 0,
        parentUuid: this.info.uuid
      };
      getFileList(params).then(res => {
        console.log(res);
        if (res.state == 100) {
          this.arrowFileList = [];
          this.iconFileList = [];
          this.allFileList = res.items;
          res.items.forEach(item => {
            if (item.typeName == "arrowFile") {
              this.arrowFileList.push(item);
            } else {
              this.iconFileList.push(item);
            }
          });
        }
      });
    },

    //分类背景样式--------------------------------------------
    styleFn(item) {
      return {
        background: `linear-gradient(90deg, ${item.start} 0%, ${item.end} 100%)`
      };
    },

    //文件校验--------------------------------------------
    validatorFn() {
      return true;
    },

    //确定提交--------------------------------------------
    async submit() {
      //表单校验--------------------------------------------
      if (!this.validatorFn()) return;
      const shopUuid = this.$store.getters.shopUuid;
      //编辑--------------------------------------------
      const data = {
        ...this.formData,
        shopUuid
      };
      const res = await inOrUpProductType(data);
      if (res.state == 100) {
        //更新的文件--------------------------------------------
        const fileList = this.iconFileList
          .concat(this.arrowFileList)
          .filter(item => item.raw);

        //要删除的文件--------------------------------------------
        this.deleteFileList = this.allFileList.filter(
          item => fileList.uuid != item.uuid
        );

        if (fileList.length !== 0) {
          this.uploadSuccessNum = 0;
          this.uploadFileNum = 0;
          this.currentUploadList = [];
          this.showProgress = true;
          //存在要更新的文件时--------------------------------------------
          fileList.forEach((fileItem, index) => {
            this.currentUploadList.push({
              loaded: 0,
              total: 0
            });
            this.uploadFileNum += 1;
            this.getUploadKey(res.items, fileItem, index);
          });
        } else {
          //不存在要更新的文件时--------------------------------------------
          this.$message({ type: "success", message: "修改成功" });
          this.dialogVisible = false;
          this.$emit("updateData");
        }
        if (this.deleteFileList.length !== 0) {
          let uuid = "";
          this.deleteFileList.forEach(item => (uuid += item.uuid + ","));
          const params = {
            uuid
          };
          delFile(params);
        }
      }
    },

    //获取上传凭证--------------------------------------------
    async getUploadKey(shopData, fileItem, index) {
      const data = {
        fileName: fileItem.name,
        fileSize: fileItem.size,
        parentUuid: shopData.uuid,
        typeName: fileItem.typeName,
        shopUuid: shopData.shopUuid
      };
      const res = await getUploadKey(data);
      if (res.state == 100) {
        let data = { ...res.items };
        data.typeName = fileItem.typeName;
        data.dataUuid = shopData.uuid;
        this.uploadKeyList.push(data);
        this.ossUpload(res.items, fileItem, index);
      }
    },

    //上传阿里云--------------------------------------------
    async ossUpload(key, fileItem, index) {
      const formData = new FormData();
      formData.append("policy", key.policy);
      formData.append("OSSAccessKeyId", key.accessid);
      formData.append("success_action_status", 200);
      formData.append("signature", key.signature);
      formData.append("key", key.dir);
      formData.append("file", fileItem.raw);
      const host = key.host;
      const res = await ossUpload(formData, host, this.uploadCallback, index);
      if (res.status === 200) {
        this.uploadSuccessNum += 1;
        if (this.uploadSuccessNum == this.uploadFileNum) {
          this.editFilePicture();
        }
      }
    },

    //上传回调--------------------------------------------
    uploadCallback(progress, index) {
      let uploadData = {
        loaded: progress.loaded,
        total: progress.total
      };
      this.currentUploadList.splice(index, 1, uploadData);
    },

    // 上传成功后编辑文件图片数据
    async editFilePicture() {
      const shopUuid = this.$store.getters.shopUuid;
      let filePath = "";
      let fileIoc = "";
      let uuid = "";
      this.uploadKeyList.forEach(item => {
        uuid = item.dataUuid;
        switch (item.typeName) {
          case "iconFile":
            filePath = item.host + "/" + item.dir;
            break;
          case "arrowFile":
            fileIoc = item.host + "/" + item.dir;
            break;
        }
      });
      const data = {
        shopUuid,
        uuid,
        ...this.formData,
        fileIoc,
        filePath
      };
      const res = await inOrUpProductType(data);
      this.$message({ type: "success", message: "发布成功" });
      this.showProgress = true;
      this.$emit("updateData");
      this.dialogVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-radio-group {
  display: flex;
  flex-wrap: wrap;
  .el-radio {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    margin: 10px;
    .color-box {
      width: 144px;
      height: 40px;
      border-radius: 5px;
    }
  }
}
</style>
